import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import Login from '../views/Login.vue'
import Home from '../views/Home.vue'

// 路由配置
const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    meta: { requiresAuth: true }
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 检查是否需要认证
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
  const isAuthenticated = localStorage.getItem('isLoggedIn') === 'true'
  
  if (requiresAuth && !isAuthenticated) {
    // 如果需要认证但未登录，重定向到登录页
    next('/login')
  } else if (to.name === 'Login' && isAuthenticated) {
    // 如果已登录且尝试访问登录页，重定向到首页
    next('/')
  } else {
    // 其他情况允许访问
    next()
  }
})

export default router